package com.wwwarehouse.common.tools;

import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;

/**
 * @创建者 chenchao.
 * @创建时间 2017/9/14 9:20
 * @描述 ${TODO}
 */

public class CharacterByteUtils {

    public static CharSequence mCharSequence;
    public static void limitLength(EditText editText,final int maxLen) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence src, int start, int end, Spanned dest, int dstart, int dend) {
                int dindex = 0;
                int count = 0;

                while (count <= maxLen && dindex < dest.length()) {
                    char c = dest.charAt(dindex++);
                    if (c < 128) {
                        count = count + 1;
                    } else {
                        count = count + 2;
                    }
                }

                if (count > maxLen) {
                    return dest.subSequence(0, dindex - 1);
                }

                int sindex = 0;
                while (count <= maxLen && sindex < src.length()) {
                    char c = src.charAt(sindex++);
                    if (c < 128) {
                        count = count + 1;
                    } else {
                        count = count + 2;
                    }
                }

                if (count > maxLen) {
                    sindex--;
                }
                mCharSequence = src.subSequence(0, sindex);
                return mCharSequence;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }


    /**
     * @param content
     * @return
     * @description 获取一段字符串的字符个数（包含中英文，一个中文算2个字符）
     */
    public static int getCharacterNum(final String content) {
        if (null == content || "".equals(content)) {
            return 0;
        } else {
            return (content.length() + getChineseNum(content));
        }
    }


    /**
     * @param s
     * @return
     * @description 返回字符串里中文字或者全角字符的个数
     */
    public static int getChineseNum(String s) {
        int num = 0;
        char[] myChar = s.toCharArray();
        for (int i = 0; i < myChar.length; i++) {
            if ((char) (byte) myChar[i] != myChar[i]) {
                num++;
            }
        }
        return num;
    }
}
